#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2020/11/17 17:40
    Desc  :
--------------------------------------
"""
import copy
import json
import os
import re

import jsonpath

import requests

from config import *
from loguru import logger

from utils.excelUtils import ExcelUtils
from utils.resultUtils import ResultUtils


def read_variable(data):
    """
    读取变量, 变量格式${{ variable_name }}
    :param data: 接口参数列表
    :return:
    """

    if data[4] != "":
        data = json.loads(data[4])
        for i in data:
            if len(re.compile("{{(.*?)}}").findall(str(data[i]))) != 0:
                for j in re.compile("{{(.*?)}}").findall(data[i]):
                    data[i] = EXTRACT_VARIABLE.get(j)
        return data


def save_variable(result, data):
    """
    保存变量
    :param result: 接口请求返回值
    :param data: 接口参数列表
    :return:
    """
    EXTRACT_VARIABLE[data[5][3:]] = jsonpath.jsonpath(result.json(), data[5])[0]


def request_api(data):
    try:
        if int(data[9]) == 0:
            headers = copy.copy(HEADERS)
            headers['Authorization'] = 'Bearer {}'.format(EXTRACT_VARIABLE.get('token'))

            res = requests.post(url = BASE_URL + data[2], data = read_variable(data),
                                headers = headers)
        else:

            res = requests.post(url = BASE_URL + data[2], data = read_variable(data))

        if data[6] != "":

            # 判断断言结构
            if jsonpath.jsonpath(res.json(), data[6])[0] == data[7]:
                status = CASE_STATUS.get(100)

                if data[5] != "":
                    # 提取参数并保存
                    try:
                        save_variable(res, data)
                    except Exception as e:
                        logger.error(e)

            else:
                status = CASE_STATUS.get(101)

        else:

            if jsonpath.jsonpath(res.json(), "$..code")[0] == 20000:
                status = CASE_STATUS.get(100)
                if data[5] != "":
                    # 提取参数并保存
                    save_variable(res, data)
            else:
                status = CASE_STATUS.get(101)

        # print(res.request.headers)
        return ResultUtils(data, status, response = res).result()

    except Exception as e:

        status = CASE_STATUS.get(102)

        return ResultUtils(data, status, errors = e).result()


if __name__ == '__main__':

    filepath = os.getcwd() + r"\case\蒙多奇超级后台接口测试.xlsx"

    for i in ExcelUtils.read_excel(filepath):
        if i[8] == 0:
            print(request_api(data = i))

